// editor.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "editor.h"
#include <sstream>
#include <cstdlib>
#include <vector>
#include "../items.h"
#include <Strsafe.h>

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name

HWND newWindow=0;


std::vector<fortress::abstractItems> allItems;

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	Item_Editor(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	Main_View(HWND, UINT, WPARAM, LPARAM);

INT_PTR CALLBACK	Save_As(HWND);
INT_PTR CALLBACK	Load(HWND);
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_EDITOR, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_EDITOR));

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg) && !IsDialogMessage(newWindow, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_EDITOR));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_EDITOR);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;

	hInst = hInstance; // Store instance handle in our global variable

//   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
//      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
	hWnd = CreateDialog(hInst, MAKEINTRESOURCE(IDD_MAIN), 0, (DLGPROC)Main_View);

	if (!hWnd)
	{
	  return FALSE;
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);
	SetMenu(hWnd,LoadMenu(hInst,MAKEINTRESOURCE(IDC_EDITOR)));

	return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}

INT_PTR CALLBACK Load(HWND hDlg)
{
	int index;
	std::ifstream loadFile("items.dat");
	boost::archive::text_iarchive ia(loadFile);
	fortress::savedItems data;
	ia >> data;
	allItems=data.getItems();
	HWND control;
	control = GetDlgItem(hDlg, IDC_ITEMS);
	for (index=SendMessage(control, LB_GETCOUNT, 0,0); index >0; index--)
	{
		SendMessage(control, LB_DELETESTRING, 0, 0);
	}
	for (std::vector<fortress::abstractItems>::iterator it = allItems.begin(); it != allItems.end(); it++)
	{
		index=SendMessage(control, LB_ADDSTRING, 0,(LPARAM)(*it).name.c_str());
	}
	return 1;
}

INT_PTR CALLBACK Save_As(HWND hDlg)
{
/*	IFileDialog *file;
    
    // CoCreate the dialog object.
	HRESULT hr = CoCreateInstance(CLSID_FileSaveDialog, 
									NULL, 
									CLSCTX_INPROC_SERVER, 
									IID_PPV_ARGS(&file));
    
	if (SUCCEEDED(hr))
	{
		// Show the dialog
		hr = file->Show(hDlg);

		if (SUCCEEDED(hr))
		{
			// Obtain the result of the user's interaction with the dialog.
			IShellItem *psiResult;
			hr = file->GetResult(&psiResult);

			if (SUCCEEDED(hr))
			{
				LPWSTR filename;
				file->GetFileName(&filename);
				char * asciiName = new char[31];
				WideCharToMultiByte(CP_ACP, 0, filename, -1, asciiName, 31,0,0);*/
				
				std::ofstream output("items.dat");
				boost::archive::text_oarchive oa(output);
				fortress::savedItems data(allItems);
				oa << data;
				// Do something with the result.
/*				psiResult->Release();
			}
		}
		file->Release();
	}*/
	return 1;
}

// Message handler for item editor
INT_PTR CALLBACK Item_Editor(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	HWND control;
	LPSTR get=new char[50];
	int num=0;
	std::ostringstream s;
	switch (message)
	{
	case 0:
		SetDlgItemText(hDlg, IDC_NAME, (LPCSTR)allItems[wParam].name.c_str());
		SetDlgItemText(hDlg, IDC_SINGULAR, (LPCSTR)allItems[wParam].singular.c_str());
		SetDlgItemText(hDlg, IDC_PLURAL, (LPCSTR)allItems[wParam].plural.c_str());
		SetDlgItemText(hDlg, IDC_DESCRIPTION, (LPCSTR)allItems[wParam].description.c_str());
		s.clear();
		s << allItems[wParam].glyph;
		SetDlgItemText(hDlg, IDC_GLYPH, (LPCSTR)s.str().c_str());
		SetDlgItemText(hDlg, IDC_COLOR, (LPCSTR)allItems[wParam].color.c_str());
		SetDlgItemInt(hDlg, IDC_DICE, allItems[wParam].dice,1);
		SetDlgItemInt(hDlg, IDC_SIDES, allItems[wParam].sides,1);
		SetDlgItemInt(hDlg, IDC_COST, allItems[wParam].cost,1);
		SetDlgItemInt(hDlg, IDC_WEIGHT, allItems[wParam].weight,1);
		s.clear();
		num = wParam;
		s << num;
		SetDlgItemInt(hDlg, IDC_ID, num,1);
		if (allItems[wParam].canCarry)
			SendDlgItemMessage(hDlg, IDC_CANCARRY, BM_SETCHECK, BST_CHECKED, 0);
		if (allItems[wParam].walkable)
			SendDlgItemMessage(hDlg, IDC_WALKABLE, BM_SETCHECK, BST_CHECKED, 0);
		if (allItems[wParam].transparent)
			SendDlgItemMessage(hDlg, IDC_TRANSPARENT, BM_SETCHECK, BST_CHECKED, 0);
		break;
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
			case IDC_CLOSE:
			case IDC_MYICON:
			case IDC_CANCEL:
				DestroyWindow(hDlg);
				newWindow=0;
				return (INT_PTR)1;
			case IDC_SAVE:
				GetDlgItemText(hDlg, IDC_ID, get, 3);
				num=atoi(get);
				GetDlgItemText(hDlg, IDC_NAME, get, 50);
				allItems[num].name=get;
				GetDlgItemText(hDlg, IDC_SINGULAR, get, 50);
				allItems[num].singular=get;
				GetDlgItemText(hDlg, IDC_PLURAL, get, 50);
				allItems[num].plural=get;
				GetDlgItemText(hDlg, IDC_DESCRIPTION, get, 50);
				allItems[num].description=get;
				GetDlgItemText(hDlg, IDC_COST, get, 50);
				allItems[num].cost=atoi(get);
				GetDlgItemText(hDlg, IDC_WEIGHT, get, 50);
				allItems[num].weight=atoi(get);
				GetDlgItemText(hDlg, IDC_DICE, get, 50);
				allItems[num].dice=atoi(get);
				GetDlgItemText(hDlg, IDC_SIDES, get, 50);
				allItems[num].sides=atoi(get);
				GetDlgItemText(hDlg, IDC_COLOR, get, 50);
				allItems[num].color=get;
				GetDlgItemText(hDlg, IDC_GLYPH, get, 50);
				allItems[num].glyph=get[0];
				if (BST_CHECKED==SendDlgItemMessage(hDlg, IDC_WALKABLE, BM_GETCHECK, 0, 0))
					allItems[num].walkable=1;
				if (BST_CHECKED==SendDlgItemMessage(hDlg, IDC_CANCARRY, BM_GETCHECK, 0, 0))
					allItems[num].canCarry=1;
				if (BST_CHECKED==SendDlgItemMessage(hDlg, IDC_TRANSPARENT, BM_GETCHECK, 0, 0))
					allItems[num].transparent=1;
				SendMessage(GetParent(hDlg), 0, num, (LPARAM)allItems[num].name.c_str());
				return (INT_PTR)1;
		}
	}
	return (INT_PTR)FALSE;
}

// Message handler for main
INT_PTR CALLBACK Main_View(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	int index=0;
	int selection=0;
	int selector=0;
	HWND control;
	WPARAM hi,lo;
	hi = HIWORD(wParam);
	lo = LOWORD(wParam);
	switch (message)
	{
	case 0:
		control = GetDlgItem(hDlg, IDC_ITEMS);
		SendMessage(control, LB_DELETESTRING, wParam, 0);
		SendMessage(control, LB_INSERTSTRING, wParam, (LPARAM)allItems[wParam].name.c_str());
		break;
	case WM_INITDIALOG:
		Load(hDlg);
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		switch(LOWORD(wParam))
		{
		case ID_FILE_OPEN:
			return Load(hDlg);
		case ID_FILE_SAVE:
		case ID_FILE_SAVEAS:
			return Save_As(hDlg);
		case IDC_ITEMS_INSERT:
			if (!IsWindow(newWindow))
			{
				control = GetDlgItem(hDlg, IDC_ITEMS);
				index=SendMessage(control, LB_ADDSTRING, 0,(LPARAM)"New");
				fortress::abstractItems newItem;
				newItem.name="New";
				newItem.cost=0;
				newItem.walkable=0;
				newItem.canCarry=0;
				newItem.transparent=0;
				newItem.dice=0;
				newItem.sides=0;
				newItem.glyph=' ';
				allItems.push_back(newItem);
				newWindow = CreateDialog(hInst, MAKEINTRESOURCE(IDD_ITEMEDITOR), hDlg, (DLGPROC)Item_Editor);
				ShowWindow(newWindow, SW_SHOW);
				SendMessage(newWindow, 0, index, 0);
			}
			break;
		case IDC_ITEMS_EDIT:
			control = GetDlgItem(hDlg, IDC_ITEMS);
			selection=0;
			index=-1;
			for (int it=0; (unsigned int)it < allItems.size(); it++)
			{
				selection=SendMessage(control, LB_GETSEL, it, 0);
				if (selection>0)
					index=it;
			}
			if (index==-1)
				break;
			if (!IsWindow(newWindow))
			{
				newWindow = CreateDialog(hInst, MAKEINTRESOURCE(IDD_ITEMEDITOR), hDlg, (DLGPROC)Item_Editor);
				ShowWindow(newWindow, SW_SHOW);				
			}
			SendMessage(newWindow, 0, index, 0);
			break;

		case IDC_ITEMS_DELETE:
			control = GetDlgItem(hDlg, IDC_ITEMS);
			selection=0;
			index=-1;
			for (int it=0; (unsigned int)it < allItems.size(); it++)
			{
				selection=SendMessage(control, LB_GETSEL, it, 0);
				if (selection>0)
					index=it;
			}
			if (index==-1)
				break;
			SendMessage(control, LB_DELETESTRING, index, 0);
			allItems.erase(allItems.begin()+index);
			break;
		case IDC_ITEMS:
			switch(HIWORD(wParam))
			{
			case LBN_SELCHANGE:
				break;
			case LBN_SETFOCUS:
				break;
			}
			break;

		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hDlg, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hDlg);
			break;
		case IDC_CLOSE:
		case IDC_MYICON:
			DestroyWindow(hDlg);
			return (INT_PTR)TRUE;
		break;

		default:
			return DefWindowProc(hDlg, message, wParam, lParam);
		}
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}
	return (INT_PTR)FALSE;
}
